package edu.ucsd.cse135.gas.action.admin;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import edu.ucsd.cse135.gas.bean.admin.UserBean;
import edu.ucsd.cse135.gas.bean.admin.UsersBean;
import edu.ucsd.cse135.gas.logic.admin.UserAdmin;
import edu.ucsd.cse135.gas.resources.Constants;

public class UserAdminAction extends DispatchAction {
	
	public ActionForward overview(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
			
		UsersBean usersBean = new UsersBean();
		
		for(int i=0; i < UserAdmin.getUsers().size(); i++)
		{
			UserBean userBean = new UserBean();
			
			userBean.setMail(UserAdmin.getUsers().get(i).getMail());
			userBean.setRole(UserAdmin.getUsers().get(i).getRole());
			
			ArrayList<UserBean> aux = new ArrayList<UserBean>();
			
			aux = usersBean.getUsers();
			
			aux.add(userBean);
			
			usersBean.setUsers(aux);
		}
		
		request.setAttribute("users", usersBean);
		
		if(usersBean.getUsers().isEmpty())
		{
			request.setAttribute("usersEmpty", true);
		}
		else
		{
			request.setAttribute("usersEmpty", false);
		}
		
		return mapping.findForward(Constants.USER_OVERVIEW);
		
	}
	
	public ActionForward create(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
				
		return mapping.findForward(Constants.CREATE_USER);
		
	}
	
	public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
		
		UserBean userForm = (UserBean)form;
		
		UserAdmin.editUser(userForm.getOldMail(), userForm.getMail(), userForm.getPassword(), userForm.getRole());
		
		return mapping.findForward(Constants.USER_OVERVIEW);
	}
	
	public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
		
		UserBean userForm = (UserBean)form;
		
		UserAdmin.deleteUser(userForm.getMail());
		
		return mapping.findForward(Constants.USER_OVERVIEW);
		
	}
}